<template>
  <page-view :title="false">
    <a-card :bordered="false">
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="showAddHomeWork">新建作业</a-button>
      </div>
      <!--table-->
      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        bordered
      >
          <span slot="status" slot-scope="text">
            <template>
              <span class="status-span success" v-if="text === 'E'" style="background-color: #ff0000">错误</span>
              <span class="status-span" v-else-if="text === 'R'" style="background-color: #adff2e">运行中</span>
              <span class="status-span" v-else-if="text === 'F'" style="background-color: #52c41a">完成</span>
              <span class="status-span" v-else style="background-color: #f6a520">等待中</span>
            </template>
          </span>

        <span slot="action" slot-scope="text, record">
            <template>
              <a @click="confirmPerformHomework(record)" v-if="record._jobState === ''">执行</a>
              <a @click="updateHomework(record)" v-if="record._jobState === 'R' || record._jobState === 'E'">刷新</a>
              <a-divider type="vertical" v-if="record._jobState !== 'F'"/>
              <a @click="confirmDelete(record)">删除</a>
            </template>
          </span>
      </s-table>
      <!--table end-->
    </a-card>

      <!--新增作业 modal-->
      <a-modal v-model="addHomeWorkModal.visible" centered destroyOnClose title="新增作业">
        <template slot="footer">
          <a-button key="back" @click="closeHomeWorkModal()">取消</a-button>
          <a-button key="submit" type="primary" :loading="addHomeWorkModal.loading" @click="subaddHomeWorkModal">
            确认
          </a-button>
        </template>
        <a-form :form="form">
          <a-form-item
            v-bind="addHomeWorkModal.formItemLayout"
            label="作业名称"
          >
            <a-input
              v-decorator="[
            'projuctName',
            { rules: [{ required: true, message: '请输入名称' }] },
          ]"
              placeholder="请输入名称"
            />
          </a-form-item>

          <a-form-item
            v-bind="addHomeWorkModal.formItemLayout"
            label="集群列表"
          >
            <a-select
              v-decorator="[
          'clusterSelect',
          { rules: [{ required: true, message: '请选择集群!' }] },
        ]"
              placeholder="请选择集群"
              @change="clusterSelectChange"
            >
              <a-select-option :value="items._id" v-for="items in addHomeWorkModal.clusterList" :key ="items._id">
                {{items._name}}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            v-bind="addHomeWorkModal.formItemLayout"
            label="上传文件"
            :required="true"
            :validate-status = "addHomeWorkModal.isUploadFile"
            :help="addHomeWorkModal.errorText"
          >
            <a-upload
              v-decorator="[
            'upload',
            {
              valuePropName: 'addHomeWorkModal.fileList',
              getValueFromEvent: normFile,
            },
            { rules: [{ required: true, message: '请上传文件' }] },
          ]"
              name="deploymentUpload"
              :fileList="addHomeWorkModal.fileList"
              :action="addHomeWorkModal.postUrl"
              list-type="text"
              :beforeUpload="uploadBeforeUpload"
              @change="deploymentUploadChange"
              :remove="removeUpload"
            >
              <a-button> <a-icon type="upload" /> 选择文件</a-button>
            </a-upload>
          </a-form-item>

          </a-form-item>

        </a-form>
      </a-modal>
      <!--新增作业 modal end-->
  </page-view>
</template>

<script>
  import { Radar, STable } from '@/components'
  import { PageView } from '@/layouts'
  // import { getRoleList, getServiceList } from '@/api/manage'
  import { getAllHomeworkList, getHpcList , subAllHomework, deleteAllHomework, performAllHomework, updateHomeworkStatus } from '@/api/aihpc'
  export default {
    name: "HomeWorkList",
    data(){
      return {
        form: this.$form.createForm(this),
        addHomeWorkModal: {
          loading: false,
          visible: false,
          hpcItem: {},
          clusterList: [], //集群数据列表
          isShowUpload: true,
          postUrl: '/remote/upload',
          fileList: [],
          isUploadFile: 'success',
          errorText:'',
          hpcId: '',
          pathUrl: '',
          formItemLayout: {
            labelCol: {
              xs: { span: 24 },
              sm: { span: 5 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 19 },
            },
          }
        },
        // 表头
        columns: [
          {
            title: '作业编号',
            dataIndex: '_workId'
          },
          {
            title: '作业名称',
            dataIndex: '_name'
          },
          {
            title: '应用',
            dataIndex: 'app',
            // sorter: true,
            // needTotal: true,
            // scopedSlots: { customRender: 'setting' },
            customRender: (text) => text._name
          },
          {
              title: '运行用户',
              dataIndex: '_owner',
              customRender: (text) => text.replace('@master', '')
              // sorter: true
          },
          {
            title: '核数',
            dataIndex: '_ncpus',
            // sorter: true
          },
          {
            title: 'CPU规格',
            dataIndex: 'machine',
            // sorter: true
            customRender: (text) => text._name
          },
          {
            title: '内存',
            dataIndex: '_mem',
            // sorter: true
          },
          {
            title: '任务进度',
            dataIndex: 'updatedAtssa',
            // sorter: true
          },
          {
            title: '运行状态',
            dataIndex: '_jobState',
            scopedSlots: { customRender: 'status' }
          },
          {
            title: '提交时间',
            dataIndex: '_timestamp',
            // sorter: true
          },
          {
            title: '运行时长',
            dataIndex: '_walltime',
            // sorter: true
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' }
          }
        ],
        tableDatas: {
          data: [],
          pageNo: 1,
          pageSize: 10,
          totalCount: 0,
          totalPage: 0
        },
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          let that = this;
          let params = {
            _id: that.$route.params.id
          }
          return getAllHomeworkList(params)
            .then(res => {
              let data = res && res.data ? res.data.rows : [];
              that.tableDatas.data = data;
              that.tableDatas.totalCount = data.length;
              return that.tableDatas
            }).catch(err => {
              that.$message.error("获取作业列表失败")
              return that.tableDatas
            })
        },
        selectedRowKeys: [],
        selectedRows: [],

        // custom table alert & rowSelection
        options: {
          alert: false,
          rowSelection: {
            selectedRowKeys: [],
            onChange: this.onSelectChange
          }
        }
      }
    },
    components: {
      STable,
      PageView
    },
    methods:{
      showAddHomeWork: function (items) {
        let that = this;
        getHpcList()
          .then((res) => {
            let data = res && res.data ? res.data.rows : [];
            that.addHomeWorkModal.clusterList = data;
            that.addHomeWorkModal.visible = true;
            that.addHomeWorkModal.hpcItem = items;
            let defulatId = data ? data[0]._id : 0
             that.form.getFieldDecorator('clusterSelect', {initialValue: defulatId})
          }).catch(err => {
            that.$message.error('获取集群列表失败');
        })
      },
      normFile(e) {
        if (Array.isArray(e)) {
          return e;
        }
        return e && e.fileList;
      },
      deploymentUploadChange: function (info) {
        if(info.file.type === 'application/zip' || info.file.type === 'application/x-zip' || info.file.type=== 'application/x-zip-compressed'){
          this.addHomeWorkModal.isShowUpload = false;
          if (info.file.status !== 'uploading') {

          }
          if (info.file.status === 'done') {
            this.$message.success(`上传成功`);
            let data = info && info.file && info.file.response ? info.file.response : ''
            this.addHomeWorkModal.pathUrl = data  ? data.path : ''
          } else if (info.file.status === 'error') {
            this.$message.error(`上传失败`);
          }

        }
        this.addHomeWorkModal.isUploadFile='success'
        this.addHomeWorkModal.errorText=''
        this.addHomeWorkModal.fileList = info.fileList;
      },
      uploadBeforeUpload: function (file) {
        const zip = file.type === 'application/zip' || file.type === 'application/x-zip' || file.type === 'application/x-zip-compressed';
        if (!zip) {
          this.$message.error('请上传zip格式文件');
        }
        this.addHomeWorkModal.fileList = []
        return zip;
      },
      removeUpload: function (){
        this.addHomeWorkModal.isShowUpload = true;
      },
      closeHomeWorkModal: function () {
        this.addHomeWorkModal.visible =false;
      },
      subaddHomeWorkModal: function (){
        let that = this;
        this.form.validateFields((err, values) => {
          if (!err) {
            if(that.addHomeWorkModal.pathUrl){
              let params = {
                _name: values ? values.projuctName : '',
                _path: that.addHomeWorkModal.pathUrl,
                _instanceId: values ? values.clusterSelect : ''
              };

              subAllHomework(params)
                .then((res) => {
                  that.$message.success('新建作业成功');
                  that.addHomeWorkModal.isUploadFile='success'
                  that.addHomeWorkModal.errorText=''
                  that.$refs.table.refresh(true);
                  that.closeHomeWorkModal();
                }).catch(err => {
                  that.$message.error('新建作业失败');
                  that.closeHomeWorkModal();
              })
            }else{
              that.addHomeWorkModal.isUploadFile='error';
              that.addHomeWorkModal.errorText='请上传文件';
              that.$message.error('请上传作业文件');
            }

          }
        })
      },
      clusterSelectChange: function (value) {
        this.addHomeWorkModal.hpcId = value;
      },
      updateHomework: function (data){
          let that = this;
          let params = {
              _id: data._id
          }
          updateHomeworkStatus(params)
          .then((res)=>{
              that.$refs.table.refresh(true)
              that.$message.success("刷新状态成功")
          }).catch((err)=>{
              that.$message.error("刷新状态失败")
          })
      },
      confirmPerformHomework(data) {
        let that = this;
        this.$confirm({
          title: `执行作业`,
          content: `是否确认执行${data._name}？`,
          okText: '确认',
          cancelText: '取消',
          centered: true,
          destroyOnClose: true,
          maskClosable: true,
          onOk() {
            that.performHomework(data);
          },
        });
      },
      performHomework: function (data) {
        let that = this;
        let params = {
          _id: data._id
        }
        performAllHomework(params).then((res)=>{
          that.$refs.table.refresh(true)
          that.$message.success("执行作业成功")
        }).catch((err)=>{
          that.$message.error("执行作业失败")
        })
      },
      confirmDelete(data) {
        let that = this;
        this.$confirm({
          title: `删除作业`,
          content: `是否确认删除${data._name}？`,
          okText: '确认',
          cancelText: '取消',
          centered: true,
          destroyOnClose: true,
          maskClosable: true,
          onOk() {
            that.deleteHomeWork(data);
          },
        });
      },
      deleteHomeWork: function (data) {
        let that = this;
        let params = {
          _id: data._id
        }
        deleteAllHomework(params).then((res)=>{
          that.$refs.table.refresh(true)
          that.$message.success("删除作业成功")
        }).catch((err)=>{
          that.$message.error("删除作业失败")
        })
      },
      getPopupContainer(trigger) {
        return trigger.parentElement;
      },
      onSelectChange: function(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
    }
  }
</script>

<style lang="less" scoped>
  .status-span{
    padding: 3px 10px;
    border-radius: 15px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    display: inline-block;
  & .success{
      background-color: #52c41a;
    }
  }
  @media (max-width: 575px){
    .status-span{
      padding: 3px 5px;
    }
  }
</style>